<?php

namespace App\Http\Controllers;

use App\Http\Resources\AdminResource;
use App\Models\Admin;
use Hash;
use Illuminate\Http\Request;

class AdminsController extends Controller
{
    public function index(Request $request, Admin $admin)
    {
        $query = $admin->query();
        if ($name = $request->name) {
            $query->name($name);
        }
        $admins = $query->paginate(request()->get('per_page', 10));
        return $this->paginationResponse(AdminResource::collection($admins));
    }

    public function store(Request $request, Admin $admin)
    {
        $this->validate($request, [
            'name' => 'required|between:3,25|regex:/^[A-Za-z0-9\-\_]+$/|unique:admins,name',
            'phone' => 'required|regex:/^1[34578][0-9]{9}$/|unique:admins,phone',
        ]);
        dd(12);
        $password = bcrypt('123456');
        $admin->name = $request->name;
        $admin->phone = $request->phone;
        $admin->password = $password;
        $admin->save();
        return $this->success(new AdminResource($admin));
    }

    public function update(Request $request, Admin $admin)
    {
        $this->validate($request, [
            'name' => 'required|between:3,25|regex:/^[A-Za-z0-9\-\_]+$/|unique:admins,name,' . $admin->id,
            'phone' => 'required|regex:/^1[34578][0-9]{9}$/|unique:admins,phone,' . $admin->id,
        ]);
        $admin->update($request->only([
            'name',
            'phone',
        ]));
        return $this->success(new AdminResource($admin));
    }

    public function destroy(Admin $admin)
    {
        $admin->delete();
        return $this->noContent();
    }


    public function me()
    {
        return $this->success(new AdminResource(\Auth::user()));
    }

    public function changePassword(Request $request)
    {
        $this->validate($request, [
            'old_password' => 'required|string',
            'new_password' => 'required|string',
        ]);
        $admin = \Auth::user();
        if (!Hash::check($request->old_password, $admin->password)) {
            return $this->failed('密码不正确', 400);
        } else {
            $admin->password = bcrypt($request->new_password);
            $admin->save();
            return $this->success(new AdminResource($admin));
        }
    }
}
